const fs = require('fs')
const path = require('path')
const express = require('express')
const router = express.Router()
const AcModel = require('../models/ac')
const EpModel = require('../models/ep')
const PlayModel = require('../models/play')
const CommentModel = require('../models/comments')
const checkLogin = require('../middlewares/check').checkLogin

// GET /ep/:epId/edit 更新ep
router.get('/:epId/edit', checkLogin, (req, res, next) => {
  const epId = req.params.epId
  const author = req.session.user._id

  EpModel.getRawEpById(epId)
    .then((ep) => {
      if (!ep) {
        throw new Error('该动漫不存在')
      }
      if (author.toString() !== ep.author._id.toString()) {
        throw new Error('权限不足')
      }
      res.render('ac/ep/edit', {
        ep
      })
    })
    .catch(next)
})

// POST ep/:epId/edit 更新分集
router.post('/:epId/edit', checkLogin, (req, res, next) => {
  const file = req.files.pic.path.split(path.sep).pop()
  const findType = file.indexOf('jpg') !== -1 || file.indexOf('gif') !== -1 || file.indexOf('png') !== -1
  const author = req.session.user._id
  const pic = findType ? file : req.fields.editPic
  const { epId } = req.params
  const { title, subTitle, url, tags, source, sort, content } = req.fields

  if (!findType) {
    fs.unlink(req.files.pic.path)
  }
  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题')
    }
  } catch (e) {
    req.flash('error', e.message)
    return res.redirect('back')
  }

  const ep = { author, title, subTitle, pic, url, tags, source, content, sort: parseInt(sort) }

  EpModel.getRawEpById(epId)
    .then((data) => {
      if (!data) {
        throw new Error('该分集不存在')
      }
      if (author.toString() !== data.author._id.toString()) {
        throw new Error('权限不足')
      }
      EpModel.updateEpById(epId, ep)
        .then(() => {
          req.flash('success', '编辑成功')
          // 编辑成功后跳转到上一页
          res.redirect(`/ep/${epId}`)
        })
        .catch(next)
    })
})

// GET /ep/:acId 单独一篇的文章页
router.get('/:epId', (req, res, next) => {
  const { epId } = req.params

  Promise.all([
    EpModel.getEpById(epId),
    PlayModel.getPlay(epId),
    CommentModel.getComments(epId), // 获取该文章所有留言
    EpModel.incPv(epId)// pv 加 1
  ])
    .then((result) => {
      const info = result[0]
      const play = result[1]
      const comments = result[2]
      const acId = info.acId

      const promises = []
      comments.forEach((elm, index) => {
        promises.push(CommentModel.getCommentReplys(elm._id).then((data) => {
          comments[index].subComment = data
        }))
      })

      Promise.all(promises).then(() => {
        Promise.all([
          AcModel.getPostById(acId), // 获取动漫信息
          EpModel.getEp(acId)
        ]).then((result) => {
          const post = result[0]
          const list = result[1]
          if (!post) {
            throw new Error('该文章不存在')
          }
          res.render('ac/ep/index', {
            acId,
            post,
            info,
            list,
            play,
            comments,
            postId: epId,
            typeId: 4 // 剧集评论
          })
        }).catch(next)
      }).catch(next)
    })
    .catch(next)
})

module.exports = router
